import { middleLogger } from '@/utils/back/devlogger';
import { pathsToRegs } from '@/utils/common';
import { NextRequest, NextResponse } from 'next/server';

const rewriteCurDomainPaths = [
  // '/_admin',  // redirect to new domain
  '/media/catalog/.*',
  '/contact-us',
  '/customer/account(/?$|/.*|\\?.*)', // for test
  '/singleLogin.php',
];
const rewriteProdDomainPaths = [
  '/blog(/?$|/.*|\\?.*)',
  '/customer/account/get-a-live-demo',
  '/customer/account/saveliveDemo',
  '/dstheme/.*',
  '/skin/.*',
  '/js/.*',
  '/admincss/.*',
  // ------------- from google docs -------------
  // '/contact-us', // dev has this page
  '/apidoc(/?$|/.*|\\?.*)',
  // '/customer/account(/?$|/.*|\\?.*)', // rewrite to current domain for test cors settings
  // '/about_us',
  '/press(/?$|/.*|\\?.*)',
  '/faq(/?$|/.*|\\?.*)',
  '/shipping_guide',
  '/about_us',
  '/privacy_statement',
  '/terms-conditions',
  '/warranty-return',
  '/policy(/?$|/.*|\\?.*)',
];

export default function rewriteMiddleware(req: NextRequest, next: Fn) {
  const pathname = req.nextUrl.pathname;

  const rewriteCurDomainRegs = pathsToRegs(rewriteCurDomainPaths);
  const rewriteProdDomainRegs = pathsToRegs(rewriteProdDomainPaths);

  const isMediaPath = pathname.startsWith('/media/catalog/');

  const newDomainResponse = (domain: string) => {
    const url = pathname + req.nextUrl.search;
    return NextResponse.rewrite(new URL(url, domain));
  };

  if (rewriteCurDomainRegs.some(reg => reg.test(pathname))) {
    middleLogger.info('rewriteMiddleware', pathname);

    if (isMediaPath) {
      if (process.env.NEXT_PUBLIC_APP_ENV === 'development') {
        return newDomainResponse(process.env.NEXT_PUBLIC_DSZ_DOMAIN!);
      }
    } else {
      return newDomainResponse(process.env.NEXT_PUBLIC_DSZ_DOMAIN!);
    }
  }

  if (rewriteProdDomainRegs.some(reg => reg.test(pathname))) {
    middleLogger.info('rewriteMiddleware', pathname);

    return newDomainResponse(process.env.NEXT_PUBLIC_DSZ_DOMAIN_PROD!);
  }

  return next(req);
}
